package com.mark.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mark.common.Const;
import com.mark.common.ServerResponse;
import com.mark.dao.UserMapper;
import com.mark.enums.UserStateEnum;
import com.mark.exception.UserException;
import com.mark.pojo.User;
import com.mark.service.IUserService;
import com.mark.util.MD5Util;
import com.mark.util.RedisShardedPoolUtil;
import com.mark.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * Created by Mark on 2018/3/22.
 * 用户模块的业务逻辑
 */

@Service("IUserService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    //1.用户注册
    @Override
    public ServerResponse<String> register(User user) throws UserException {
        //校验用户名是否已经存在
        ServerResponse<String> validResponse = checkValid(user.getUsername(), UserStateEnum.USERNAME.getType());
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        //校验邮箱是否已经存在
        validResponse = checkValid(user.getEmail(), UserStateEnum.EMAIL.getType());
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));//密码加密
        user.setRole(UserStateEnum.ROLE_CUSTOMER.getRole());//设置注册身份为普通用户
        user.setEnableStatus(1);//默认值为1
        int resultCount;
        try {
            resultCount = userMapper.insert(user);
        } catch (Exception e) {
            throw new UserException("register",e.getClass()+e.getMessage());
        }
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败！");
        }
        return ServerResponse.createBySuccessMessage("注册成功！");
    }

    //校验用户信息
    public ServerResponse<String> checkValid(String str, String type) throws UserException {
        if (UserStateEnum.USERNAME.getType().equals(type)) {//校验用户名
            try {
                if (userMapper.checkUserName(str) > 0) {
                    return ServerResponse.createByErrorMessage("抱歉该用户名已经被注册！");
                }
            } catch (Exception e) {
                throw new UserException("checkValid",e.getClass()+e.getMessage());
            }
        }
        if (UserStateEnum.EMAIL.getType().equals(type)) {//校验邮箱
            try {
                if (userMapper.checkEmail(str) > 0) {
                    return ServerResponse.createByErrorMessage("邮箱已经被注册！");
                }
            } catch (Exception e) {
                throw new UserException("checkValid",e.getClass()+e.getMessage());
            }
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    //2.用户登录
    @Override
    public ServerResponse<User> login(String username, String password)  {
        try {
            int resultCount = userMapper.checkUserName(username);
            if (resultCount != 1) {
                return ServerResponse.createByErrorMessage("用户名不存在");
            } else {
                password = MD5Util.MD5EncodeUtf8(password);//密码加密
                User user = userMapper.selectLogin(username, password);
                if (user == null) {
                    return ServerResponse.createByErrorMessage("密码错误！请重新登录");
                }
                if(user.getEnableStatus() == 0){//用户的状态为已经拉黑状态
                    return ServerResponse.createByErrorMessage("登录失败！该账号已经被管理撤销。原因："+user.getRemark());
                }
                return ServerResponse.createBySuccess("登录成功", user);
            }
        }catch (Exception e){
            throw new UserException("login",e.getClass()+e.getMessage());
        }
    }

    @Override
    public ServerResponse<UserVo> getInfo(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user != null) {
            user.setPassword(StringUtils.EMPTY);
            UserVo userVo = new UserVo();
            userVo = userVo.assembleUserVo(user);
            return ServerResponse.createBySuccess(userVo);
        }
        return ServerResponse.createByErrorMessage("当前用户不存在！");
    }

    //根据用户名查询到问题
    @Override
    public ServerResponse<String> selectQuestion(String username) throws UserException {
        try {
            //先验证用户信息
            ServerResponse validResponse = checkValid(username, UserStateEnum.USERNAME.getType());
            if (validResponse.isSuccess()) {//字段为空返回true
                return ServerResponse.createByErrorMessage("用户名不存在!");
            } else {
                String question = userMapper.selectQuestionByUserName(username);
                if (StringUtils.isNotBlank(question)) {
                    return ServerResponse.createBySuccessMessage(question);
                }
                return ServerResponse.createByErrorMessage("找回密码的问题为空");
            }
        }catch (UserException e){
            throw new UserException("selectQuestion",e.getClass()+e.getMessage());
        }
    }

    //根据用户名，问题，答案判断时候回答是否正确
    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) throws UserException {
        try {
            int resultCount = userMapper.checkAnswer(username, question, answer);
            if (resultCount > 0) {//回答正确
                String forgetToken = UUID.randomUUID().toString();
                //TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
                RedisShardedPoolUtil.setEx(Const.TOKEN_PREFIX+username,forgetToken,60*30);//将Token保存到Redis缓存
                return ServerResponse.createBySuccess(forgetToken);
            }
            return ServerResponse.createByErrorMessage("回答错误!");
        }catch(Exception e){
            throw new UserException("checkAnswer",e.getClass()+e.getMessage());
        }
    }

    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) throws UserException {
        //校验当前用户
        ServerResponse validResponse = checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {//用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        //String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        String token = RedisShardedPoolUtil.get(Const.TOKEN_PREFIX+username);
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("token无效或已经过期");
        }
        if (StringUtils.equals(forgetToken, token)) {
            passwordNew = MD5Util.MD5EncodeUtf8(passwordNew);//密码加密
            int rowCount = userMapper.updatePasswordByUsername(username, passwordNew);
            if (rowCount > 0) {
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        } else {
            return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) throws UserException {
        try {
            //防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户
            passwordNew = MD5Util.MD5EncodeUtf8(passwordNew);//密码加密
            passwordOld = MD5Util.MD5EncodeUtf8(passwordOld);
            //检查旧密码
            int resultCount = userMapper.checkPassword(passwordOld, user.getId());
            if (resultCount == 0) {
                return ServerResponse.createByErrorMessage("输入的旧密码不正确");
            }
            user.setPassword(passwordNew); //更新密码
            int updateCount = userMapper.updateByPrimaryKeySelective(user);
            if (updateCount > 0) {
                return ServerResponse.createBySuccessMessage("更新密码成功！");
            }
            return ServerResponse.createByErrorMessage("更新密码失败！");
        } catch (Exception e) {
            throw new UserException("resetPassword",e.getClass()+e.getMessage());
        }
    }

    @Override
    public ServerResponse<UserVo> updateInformation(User user) throws UserException {
        try {
            //username是不能被更新的
            //email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
            int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
            if (resultCount > 0) {
                return ServerResponse.createByErrorMessage("该邮箱已经被注册！请重新输入新的邮箱");
            }
            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setEmail(user.getEmail());
            updateUser.setPhone(user.getPhone());
            updateUser.setQuestion(user.getQuestion());
            updateUser.setAnswer(user.getAnswer());
            int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
            if (updateCount > 0) {
                UserVo userVo = new UserVo();
                updateUser = userMapper.selectByPrimaryKey(user.getId());
                userVo = userVo.assembleUserVo(updateUser);
                return ServerResponse.createBySuccess("更新个人信息成功",userVo);
            }
            return ServerResponse.createByErrorMessage("更新个人信息失败");
        }catch (Exception e){
            throw new UserException("updateInformation",e.getClass()+e.getMessage());
        }
    }

    //更新用户头像地址
    @Override
    public ServerResponse updateImageUrl(Integer currentUserId, String imageUrl) {
        try {
            User user = userMapper.selectByPrimaryKey(currentUserId);
            if (user != null) {
                user.setUserImg(imageUrl);
                int effectNumber = userMapper.updateByPrimaryKeySelective(user);
                if (effectNumber > 0) {
                    UserVo userVo = new UserVo();
                    userVo = userVo.assembleUserVo(user);
                    return ServerResponse.createBySuccess(userVo);
                }
            }
            return ServerResponse.createByErrorMessage("更新头像失败");
        }catch(Exception e){
            throw new UserException("updateImageUrl",e.getMessage());
        }
    }


    //------------------------以下是实现后台接口业务的接口的实现------------------------------------------
    @Override
    public ServerResponse getUserList(int pageNum, int pageSize) {
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<User> userList = userMapper.selectList();
            List<UserVo> userVoList = Lists.newArrayList();
            for(User user : userList){
                UserVo userVo = new UserVo();
                userVo = userVo.assembleUserVo(user);
                userVoList.add(userVo);
            }
            PageInfo pageResult = new PageInfo(userList);
            pageResult.setList(userVoList);
            return ServerResponse.createBySuccess(pageResult);
        }catch(Exception e){
            throw new UserException("getUserList",e.getClass()+e.getMessage());
        }
    }
    //2.用户的状态的改变：正常用户<--->拉黑用户
    @Override
    public ServerResponse setUserEnableStatus(Integer userId, Integer newStatus, String remark) {
        try {
            int resultCount = userMapper.updateStatusByPrimaryKey(userId, remark, newStatus);
            if (resultCount > 0) {
                return ServerResponse.createBySuccess("更新用户状态成功");
            }
            return ServerResponse.createByErrorMessage("更改用户状态失败");
        }catch(Exception e){
            throw new UserException("setUserEnableStatus",e.getClass()+e.getMessage());
        }
    }

    //3.搜索用户信息（姓名模糊查询，ID，状态）
    @Override
    public ServerResponse searchUsers(int pageNum, int pageSize, String userName, Integer userId, Integer status) {
        try{
            PageHelper.startPage(pageNum,pageSize);
            if(StringUtils.isNotBlank(userName)){
                userName = new StringBuilder().append("%").append(userName).append("%").toString();
            }
            List<User> userList = userMapper.searchUsers(userName,userId,status);
            List<UserVo> userVoList = Lists.newArrayList();
            for(User user : userList){
                UserVo userVo = new UserVo();
                userVo = userVo.assembleUserVo(user);
                userVoList.add(userVo);
            }
            PageInfo pageResult = new PageInfo(userList);
            pageResult.setList(userVoList);
            return ServerResponse.createBySuccess(pageResult);
        }catch(Exception e){
            throw new UserException("searchUsers",e.getClass()+e.getMessage());
        }
    }


}
